import Chart from 'chart.umd.min.js';

function handlePeriod(ak_code, period) {
    // 创建模态框
    createChartModal(ak_code, period);

    // 从后端获取实际数据
    fetchRealData(ak_code, period)
        .then(realData => {
            // 渲染图表
            renderChart(ak_code, period, realData);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            // 如果获取真实数据失败，使用模拟数据作为备选
            const mockData = generateMockData(period);
            renderChart(ak_code, period, mockData);
        });
}

// 新增：从后端获取实际数据的函数
function fetchRealData(ak_code, period) {
    return new Promise((resolve, reject) => {
        // 构造请求URL，添加查询参数
        // 例如限制日线数据只返回最近60条记录
        let limit = '';
        if (period === 'daily') {
            limit = '?limit=80';
        } else if (period === 'weekly') {
            limit = '?limit=60';  // 一年的周线数据
        } else if (period === 'monthly') {
            limit = '?limit=60';  // 两年的月线数据
        }

        const url = `/api/futures/history/${ak_code}/${period}/${limit}`;

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                // 处理后端返回的数据
                resolve(data);
            })
            .catch(error => {
                reject(error);
            });
    });
}

function createChartModal(ak_code, period) {
    // 如果模态框已存在，先移除
    if (document.getElementById('chartModal')) {
        document.getElementById('chartModal').remove();
    }

    // 定义周期名称
    const periodNames = {
        'daily': '日线',
        'weekly': '周线',
        'monthly': '月线'
    };

    const modalHtml = `    <div id="chartModal" style="display: block; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: hidden; background-color: rgba(0,0,0,0.4);">
        <div style="background-color: #fefefe; margin: 5% auto; padding: 20px; border: 1px solid #888; width: 80%; height: 75%; border-radius: 5px; display: flex; flex-direction: column; box-sizing: border-box;">
            <div style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 10px; border-bottom: 1px solid #eee;">
                <h5 style="margin: 0;">${ak_code} ${periodNames[period]} 图表</h5>
                <span id="closeModal" style="color: #aaa; font-size: 28px; font-weight: bold; cursor: pointer;">&times;</span>
            </div>
            <div style="padding: 15px 0; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
                <canvas id="priceChart" style="flex: 1; min-height: 0; width: 100% !important; height: 100% !important;"></canvas>
            </div>
            <div style="padding-top: 10px; border-top: 1px solid #eee;">
                <button id="closeModalBtn" style="background-color: #888; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">关闭</button>
            </div>
        </div>
    </div>`;

    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // 添加关闭事件
    document.getElementById('closeModal').onclick = function() {
        closeModal();
    };

    document.getElementById('closeModalBtn').onclick = function() {
        closeModal();
    };

    // 点击模态框外部关闭
    document.getElementById('chartModal').onclick = function(event) {
        if (event.target === this) {
            closeModal();
        }
    };

    // ESC键关闭
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });
}

function closeModal() {
    const modal = document.getElementById('chartModal');
    if (modal) {
        modal.remove();
    }

    // 更安全地销毁图表
    if (window.priceChart && typeof window.priceChart.destroy === 'function') {
        window.priceChart.destroy();
    }
    window.priceChart = null;

    // 注意：这里不能移除匿名函数的事件监听器，需要重构代码来正确移除
}

function generateMockData(period) {
    // 生成模拟数据
    const data = [];
    const labels = [];
    let baseValue = 1000;
    const now = new Date();

    let points = 30;
    if (period === 'weekly') points = 52;
    if (period === 'monthly') points = 24;

    for (let i = points; i >= 0; i--) {
        let date;
        if (period === 'daily') {
            date = new Date(now);
            date.setDate(date.getDate() - i);
            labels.push(date.toISOString().split('T')[0]);
        } else if (period === 'weekly') {
            date = new Date(now);
            date.setDate(date.getDate() - i * 7);
            labels.push(date.toISOString().split('T')[0]);
        } else { // monthly
            date = new Date(now);
            date.setMonth(date.getMonth() - i);
            labels.push(date.toISOString().slice(0, 7));
        }

        // 模拟价格波动
        const change = (Math.random() - 0.5) * 20;
        baseValue += change;
        data.push(parseFloat(baseValue.toFixed(2)));
    }

    return { labels, data };
}

function renderChart(ak_code, period, chartData) {
    // 等待模态框完全显示后再渲染图表
    setTimeout(() => {
        const canvas = document.getElementById('priceChart');
        const ctx = canvas.getContext('2d');

        // 如果已有图表实例，先销毁
        if (window.priceChart && typeof window.priceChart.destroy === 'function') {
            window.priceChart.destroy();
        }

        // 确保Chart.js已经加载
        if (typeof Chart !== 'undefined') {
            window.priceChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        label: `${ak_code} 价格走势`,
                        data: chartData.data,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1,
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false
                        }
                    }
                }
            });
        } else {
            console.error('Chart.js is not loaded');
        }
    }, 300);
}